package www.com.library.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Looper;

import www.com.library.app.Logger;


/**
 * 网络接收广播器
 *
 * @author Administrator
 */
public class NetworkReceiver extends BroadcastReceiver {

    private IntentFilter mConnectivityFilter;
    private NetWorkListener mCallback;
    private Handler mHandler;

    public NetworkReceiver() {
        /* Registers BroadcastReceiver to track network connection changes. */
        mConnectivityFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    }

    @Override
    public void onReceive(final Context context, final Intent intent) {
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // 部分手机 如，小米5S 在锁屏5分钟左右，解锁后立即收到该通知，获取网络状态为false，需使用handler转发重新获取网络状态。
                final boolean networkReady = NetworkMonitor.isNetworkReady(context);
                if (null != mCallback) {
                    mCallback.onNetWorkState(networkReady);
                }
            }
        }, 100);
    }

    /**
     * 网络监听广播注册
     */
    public void register(Context context, NetWorkListener callback) {
        if (mConnectivityFilter != null) {
            context.registerReceiver(this, mConnectivityFilter);
        }
        this.mCallback = callback;
    }

    /**
     * 网络监听广播注销
     */
    public void unregister(Context context) {
        // Unregisters BroadcastReceiver when app is destroyed.
        try {
            context.unregisterReceiver(this);
        } catch (IllegalArgumentException e) {
            Logger.e(e);
        }
    }

    /**
     * 网络监听接口
     */
    public interface NetWorkListener {
        /**
         * 网络监听接口回调
         *
         * @param hasNetWork
         */
        void onNetWorkState(boolean hasNetWork);
    }
}